package com.leyou.page.scheduler;


import com.leyou.auth.client.AuthClient;
import com.leyou.page.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class AppTokenScheduler {
    @Autowired
    private AuthClient authClient;
    @Autowired
    private JwtProperties jwtProperties;

    //添加一个成员变量，存储申请到token
    private String appToken;

    /**
     * token刷新间隔
     */
    private static final long TOKEN_REFRESH_INTERVAL = 86400000L; //24小时
    /**
     * 1）固定频率任务（每隔x秒/分/日）
     *   fixedRate: 毫秒
     */
    /**
     * token获取失败后重试的间隔
     */
    private static final long TOKEN_RETRY_INTERVAL = 10000L;
    @Scheduled(fixedRate = TOKEN_RETRY_INTERVAL )
    public void appToken(){
      while (true){
          try {
              String appToken = authClient.authorization(jwtProperties.getApp().getServiceName(), jwtProperties.getApp().getSecret());
              this.appToken=appToken;
              log.info("申请服务陈功,服务名："+jwtProperties.getApp().getServiceName());
              break;
          } catch (Exception e) {
              e.printStackTrace();
              log.info("申请服务失败,原因"+e.getMessage());
              //申请token，则隔10秒后重试
              try {
                  Thread.sleep(TOKEN_RETRY_INTERVAL);
              } catch (InterruptedException e1) {
                  e1.printStackTrace();
              }
          }
      }
    }
    public String  getAppToken(){
        return appToken;
    }
}
